from fastapi import APIRouter, HTTPException, Request
from models.schemas import QueryRequest, RAGResponse, DocumentResponse, DocRequest, AddTextsRequest, DelRequest, \
    UpdateTextsRequest, DelCtRequest
from services.rag_chain import RAGChain
router = APIRouter()


@router.post("/query", response_model=RAGResponse)
async def query_rag(request: Request, query: QueryRequest):
    try:
        # 从应用状态获取向量服务
        vector_service = request.app.state.vector_service
        # 在请求时创建 RAGChain 实例
        rag_chain = RAGChain(vector_service)

        result = await rag_chain.query(query.text,query.session_id)
        return RAGResponse(
            answer=result["answer"],
            sources=[
                DocumentResponse(
                    content=source["content"],
                    metadata=source["metadata"]
                ) for source in result["sources"]
            ]
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        print(f"服务器错误: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务器错误: {str(e)}")


@router.post("/add-texts")
async def add_texts(request: Request, add_request: AddTextsRequest):
    try:
        # 从应用状态获取向量服务
        vector_service = request.app.state.vector_service

        rag_chain = RAGChain(vector_service)

        return await rag_chain.add_text(add_request)

    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器错误: {str(e)}")

@router.post("/add-qa")
async def add_qa(request: Request, add_request: AddTextsRequest):
    try:
        # 从应用状态获取向量服务
        vector_service = request.app.state.vector_service

        rag_chain = RAGChain(vector_service)

        return await rag_chain.add_qa(add_request)

    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器错误: {str(e)}")


@router.get("/rag/all-texts")
async def get_all_texts(request: Request):
    vector_service = request.app.state.vector_service
    rag_chain = RAGChain(vector_service)
    docs = await rag_chain.get_all_documents_as_map()
    return docs

@router.post("/rag/del-texts")
async def del_texts(request: Request, del_request: DelRequest):
    vector_service = request.app.state.vector_service
    rag_chain = RAGChain(vector_service)
    del_ct = await rag_chain.delete_documents_by_ids(del_request.doc_ids)
    return {"data": del_ct,"msg": "删除成功","code": 200}

@router.post("/rag/update-text")
async def update_text(request: Request, update_request: UpdateTextsRequest):
    vector_service = request.app.state.vector_service
    rag_chain = RAGChain(vector_service)
    docs = await rag_chain.update_document(update_request.doc_id,update_request)
    return docs


@router.post("/rag/del-context")
async def del_context(request: Request, del_request: DelCtRequest):
    vector_service = request.app.state.vector_service
    rag_chain = RAGChain(vector_service)
    del_ct = await rag_chain.delete_context_by_id(del_request.sender_id,del_request.rec_id)
    return {"data": del_ct,"msg": "删除成功","code": 200}